import React, { Component } from 'react'
import List from './List/index'
import PayBar from './PayBar/index'
import { UpdateProductType, CartProductType } from '@/models/types'
import { apiGetCart, postEditCart } from '@/servers/cart'
interface Props {

}
interface State {
  data: CartProductType[]
}

export default class Cart extends Component<Props, State> {
  state = {
    data: []
  }
  updateProduct = (payload: UpdateProductType) => {
    const { id, index, count, checked } = payload
    /**保存一份data
     * count === 0 直接删除
     */
    const data = [...this.state.data]
    if (count === 0) {
      data.splice(index, 1)
    } else {
      // 合并
      Object.assign(data[index], payload)
    }
    // 发送后端更改Cart请求， 请求成功后更改数据
    postEditCart({ id, count }).then(() => {
      // setState参数必须是对象
      this.setState({ data })
    })
  }

  componentDidMount() {
    apiGetCart().then(data => {
      /**
       * setState({data: xx})
       */
      this.setState({ data: data.list.data })
    })
  }
  trackCheckedAll = (checked: boolean) => {
    const data = this.state.data.map((item: CartProductType) => {
      return item = {
        ...item,
        checked
      }
    });
    this.setState({ data })
  }
  /**
   * List
   * PayBar 
   */
  render() {
    return (
      <div>
        <List updateProduct={this.updateProduct} data={this.state.data} ></List>
        <PayBar data={this.state.data} trackCheckedAll={this.trackCheckedAll} ></PayBar>
      </div>
    )
  }
}
